package com.tongbo.mobilesafe.ui;

import java.io.File;

import com.tongbo.mobilesafe.R;
import com.tongbo.mobilesafe.domain.UpdateInfo;
import com.tongbo.mobilesafe.engine.DownLoadFileTask;
import com.tongbo.mobilesafe.engine.UpdateInfoService;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SplashActivity extends Activity {
	private static final String TAG = "SplashActivity";
	private TextView tv_splash_version;
	private LinearLayout ll_splash_main;
	//更新的信息
	private UpdateInfo info;
	//下载对话框
	private ProgressDialog pd;
	private String versionText;
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			//判断服务器的版本号和客户端的版本号是否相同
			if(isNeedUpdate(versionText)){//版本号不同，需要升级
				Log.i(TAG, "弹出来升级对话框");
				showUpdataDialog();
			}
		}
		
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//取消掉标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.splash);
		
		pd = new ProgressDialog(this);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage("正在下载...");
		
		ll_splash_main = (LinearLayout)this.findViewById(R.id.ll_splash_main);
		tv_splash_version = (TextView)this.findViewById(R.id.tv_splash_version);
		versionText = getVersion();
		//让当前的activity延迟两秒钟检查更新
		new Thread(){
			@Override
			public void run() {
				super.run();
				try {
					sleep(2000);
					handler.sendEmptyMessage(0);//发一条空消息给主线程
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}.start();
		
		tv_splash_version.setText(versionText);
		AlphaAnimation aa = new AlphaAnimation(0.0f, 1.0f);
		aa.setDuration(2000);
		ll_splash_main.setAnimation(aa);
		
		//完成窗体的全屏显示
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}
	/**
	 * 升级的对话框
	 */
	private void showUpdataDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setIcon(R.drawable.icon5);
		builder.setTitle("升级提醒");
		builder.setMessage(info.getDescription());
		builder.setCancelable(false);//让用户不能取消对话框
		builder.setPositiveButton("确定", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.i(TAG, "下载apk文件"+info.getApkurl());
				if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
					DownLoadFileThreadTask task = new DownLoadFileThreadTask(info.getApkurl(),"/sdcard/new.apk");
					pd.show();
					new Thread(task).start();
				}else {
					Toast.makeText(getApplicationContext(), "SD卡不可用", 1).show();
					loadMainUI();
				}
			}
		});
		builder.setNegativeButton("取消", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.i(TAG, "用户取消，进入主界面");
				loadMainUI();
			}
		});
		//显示出对话框
		builder.create().show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	/**
	 * 
	 * @param versionText
	 * 		当前客户端的版本号信息
	 * @return 是否需要更新
	 */
	public boolean isNeedUpdate(String versionText){
		UpdateInfoService service = new UpdateInfoService(this);
		try {
			info = service.getUpdateInfo(R.string.updateurl);
			if(versionText.equals(info.getVersion())){
				Log.i(TAG, "版本相同,无需升级, 进入主界面");
				loadMainUI();
				return false;
			}else{
				Log.i(TAG, "版本不同,需要升级");
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "获取更新信息异常", 0).show();
			Log.i(TAG, "获取更新信息异常, 进入主界面");
			loadMainUI();
			return false;
		}
	}
	/**
	 * 获取当前应用程序的版本号
	 * @return
	 */
	private String getVersion(){
		try {
			PackageManager manager = getPackageManager();
			PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
			return info.versionName;
		} catch (Exception e) {
			e.printStackTrace();
			return "版本号未知";
		}
	}
	/**
	 * 进入主界面
	 */
	private void loadMainUI(){
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		finish();//把当前activity从任务栈里面移除
	}
	
	private class DownLoadFileThreadTask implements Runnable{
		private String path;//要下载的服务器上的apk文件的路径
		private String filePath;//保存到本地的apk文件的路径
		public DownLoadFileThreadTask(String path, String filePath) {
			super();
			this.path = path;
			this.filePath = filePath;
		}
		@Override
		public void run() {
			try {
				Looper.prepare();
				File file = DownLoadFileTask.getFile(path, filePath,pd);
				Log.i(TAG, "下载成功");
				pd.dismiss();
				install(file);//安装apk
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(getApplicationContext(), "下载文件失败", 0).show();
				pd.dismiss();
				loadMainUI();
			}
		}
	}
	/**
	 * 安装apk
	 * @param file 要安装的apk
	 */
	private void install(File file){
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		finish();
		startActivity(intent);
	}
}